﻿using MS.Cache;
using MS.Entities;
using MS.Enums.Common;
using MS.Identity;
using MS.Utility.Common;
using MS.Utility.Config;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace MS.Logic
{
    public partial class MS_Base_RoleFunctionLogic
    {
        /// <summary>
        /// 保存角色权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="functionIdArr"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public bool SaveRoleFunction(int roleId, List<int> functionIdArr, long uid)
        {
            MS_Base_RoleLogic roleLogic = MS_Base_RoleLogic.GetInstance();
            var role = roleLogic.GetById(roleId);
            if(role == null)
            {
                return false;
            }

            List<MS_Base_RoleFunction> list = new List<MS_Base_RoleFunction>();
            foreach (int functionId in functionIdArr)
            {
                MS_Base_RoleFunction roleFunction = new MS_Base_RoleFunction();
                roleFunction.RoleId = roleId;
                roleFunction.FunctionId = functionId;
                roleFunction.Status = (int)Status.Normal;
                roleFunction.CreateTime = DateTimeHelper.GetTime(DateTime.Now);
                roleFunction.CreateUid = uid;
                roleFunction.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
                roleFunction.UpdateUid = uid;
                list.Add(roleFunction);
            }
            //清空缓存
            RemoveCache(roleId);

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
            {
                try
                {
                    this.Remove(x => x.RoleId == roleId);
                    ms_Base_RoleFunctionDal.AddRange(list);
                    role.UpdateTime = DateTimeHelper.GetTime(DateTime.Now);
                    role.UpdateUid = uid;
                    roleLogic.Save(role);
                    scope.Complete();
                    return true;
                }
                catch
                {
                    throw;
                }
            }

        }
        /// <summary>
        /// 清除缓存
        /// </summary>
        /// <param name="roleId"></param>
        private void RemoveCache(int roleId)
        {
            //清空LoginUser缓存
            MS_Base_UserRoleLogic userRoleLogic = MS_Base_UserRoleLogic.GetInstance();
            List<MS_Base_UserRole> userRoleList = userRoleLogic.GetListByQuery(x => x.RoleId == roleId && x.Status == (int)Status.Normal, null, false);
            List<string> keys = (from o in userRoleList select CacheConfig.LoginUserKey + o.Uid.ToString()).ToList();
            CacheAdapter.Cache.RemoveAll(keys);
        }
    }
}
